package cn.mrlong.base.utils.websocket

import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.util.Log


/**
 * 服务中监听websocket消息
 * 注意 android 保活服务
 */
class WebSocketService : Service(), WSManger.WebSocketCallBack {
    private val ACTION_MESSAGE_RECEIVED = "cn.mrlong.websocket.ACTION_MESSAGE_RECEIVED"
    private val ACTION_MESSAGE_CLOSE = "cn.mrlong.websocket.ACTION_MESSAGE_CLOSE"
    private val ACTION_MESSAGE_ERROR = "cn.mrlong.websocket.ACTION_MESSAGE_ERROR"
    private val ACTION_MESSAGE_OPEN = "cn.mrlong.websocket.ACTION_MESSAGE_OPEN"
    private val channel_id: String = "0x10012";
    private val channel_name: String = "通讯服务";
    private var handleMessage: HandleMessage? = null
    override fun onOpen() {

    }

    override fun onClose() {

    }

    override fun onError(t: Throwable) {

    }

    override fun onMessage(text: String) {
        handleMessage?.handleMessage(text)
    }

    override fun onConnect(status: ConnectStatus?) {

    }


    companion object {
        private const val GRAY_SERVICE_ID = 1001
        private var wsUrl: String =
            "wss://emdctest.healthlink.cn/websocket?deviceId=12345678&centerId=200000"

        /**
         * 启动服务
         */
        fun start(context: Context, wsPath: String? = null, userId: String?, centerId: String?) {
            if (null != wsPath) {
                var path = wsPath
                if (path.contains("https://")) {
                    path = path.replace("https://", "wss://")
                }
                if (path.contains("http://")) {
                    path = path.replace("http://", "wss://")
                }
                if (path.contains("emdc-app/")) {
                    path = path.replace("emdc-app/", "")
                }
                if (!path.contains("websocket")) {
                    path += "websocket"
                }
                wsUrl = "${path}?deviceId=${userId}&centerId=${centerId}"
            }
            Log.e("WebSocket==>", "" + wsUrl)
            context.startService(Intent(context, WebSocketService::class.java))
        }

        fun stop(context: Context) {
            try {
                context.stopService(Intent(context, WebSocketService::class.java))

            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onCreate() {
        super.onCreate()
        Log.e("==>", "启动服务 websocket")
        //处理message对象
        handleMessage = HandleMessage(this)
        //初始化并连接
        initSocketClient();

    }

    private fun initSocketClient() {
        WSManger
            .instance
            .wsUrl(wsUrl)//设置wss地址
            .setHeartTime(10 * 1000)//设置心跳 默认60 * 1000
            .setSocketCallBack(this)//设置数据回调监听
            .setUserAgent(Tools.getUserAgent(this))//设置userAgent 默认是okhttp字符串
            .connect()//开始连接
    }


    override fun onDestroy() {
        super.onDestroy()
        WSManger.instance.close()
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
}